import argparse,os,openpyxl,shutil,configparser,time,datetime,sys
from lxml import etree
class ATS:
    def __init__(self):
        self.parser=argparse.ArgumentParser()
        self.parser.add_argument('-subitem',type=str,help="设置需要跑的项目")
        self.parser.add_argument('-cycle', type=int, help="设置需要跑的圈数")
        self.parser.add_argument('-delay', type=int, help="设置在OS下delay的时间")
        self.parser.add_argument('-suspend', type=int, help="设置duration时间")
        self.parser.add_argument('-stoponfail', type=str, help="设置on或者off", default='off')
        self.winLRfolder_tool_path =os.path.dirname(os.path.abspath(sys.argv[0]))#获取当前路径返回比如log.exe放在D盘dist里就返回放在D:\items\LNB_ATS\dist
        self.winLR_tool_path= os.path.join(self.winLRfolder_tool_path, 'wiLongRun','wiLongRun_x64.exe')
        self.info = configparser.ConfigParser()
        self.info.read(os.path.join(self.winLRfolder_tool_path, 'wiLongRun','info.ini'))
    def copy_log_to_histroy(self):
        output_dir= os.path.join(self.winLRfolder_tool_path, 'wiLongRun','output')
        try:
            for item in os.listdir(output_dir):
                item_path = os.path.join(output_dir, item)
                shutil.move(item_path, os.path.join(self.winLRfolder_tool_path, 'wiLongRun','logs_history'))
        except Exception as e:
            pass
    def edit_Scenario_and_run(self):
        arg = self.parser.parse_args()
        self.info.set('config', 'pmclass',arg.subitem)
        self.info.set('config', 'cycle', str(arg.cycle))
        self.info.set('config', 'maxloopresult', 'Loop'+str(arg.cycle)+'.Result')
        now_date = datetime.datetime.now()
        now_date_str = now_date.strftime("%Y-%m-%d-%H-%M-%S")
        os.makedirs(os.path.join(self.winLRfolder_tool_path, 'Result', now_date_str), exist_ok=True)
        self.info.set('config', 'nowtime', now_date_str)
        with open(os.path.join(self.winLRfolder_tool_path, 'wiLongRun','info.ini'), 'w') as configfile:
            self.info.write(configfile)
        parser_xml = etree.XMLParser(remove_blank_text=True)
        if arg.subitem=='S4':
            script_path =os.path.join(self.winLRfolder_tool_path, 'wiLongRun','S4.Scenario')
            tree = etree.parse(script_path, parser_xml)
            cycle = tree.find('//MaxLoops')
            cycle.text = str(arg.cycle)
            if arg.stoponfail=='on':
                stoponfail = tree.find('//MaxFailsEnabled')
                stoponfail.text = 'true'
            elif arg.stoponfail=='off':
                stoponfail = tree.find('//MaxFailsEnabled')
                stoponfail.text = 'false'
            DelayAfterResumed = tree.find('//DelayAfterResumed')
            DelayAfterResumed.text = str(arg.delay)
            suspend=tree.find('//SleepTime')
            suspend.text = str(arg.suspend)
            tree.write(script_path, encoding='utf-8', pretty_print=True, xml_declaration=True)
            os.system(f'{self.winLR_tool_path} start {script_path}')
        elif arg.subitem=='Cb':
            script_path = os.path.join(self.winLRfolder_tool_path, 'wiLongRun', 'Coldboot.Scenario')
            tree = etree.parse(script_path, parser_xml)
            cycle = tree.find('//MaxLoops')
            cycle.text = str(arg.cycle)
            if arg.stoponfail == 'on':
                stoponfail = tree.find('//MaxFailsEnabled')
                stoponfail.text = 'true'
            elif arg.stoponfail == 'off':
                stoponfail = tree.find('//MaxFailsEnabled')
                stoponfail.text = 'false'
            DelayAfterResumed = tree.find('//DelayAfterResumed')
            DelayAfterResumed.text = str(arg.delay)
            suspend=tree.find('//SleepTime')
            suspend.text = str(arg.suspend)
            tree.write(script_path, encoding='utf-8', pretty_print=True, xml_declaration=True)
            os.system(f'{self.winLR_tool_path} start {script_path}')
        elif arg.subitem=='Wb':
            script_path = os.path.join(self.winLRfolder_tool_path, 'wiLongRun', 'Warmboot.Scenario')
            tree = etree.parse(script_path, parser_xml)
            cycle = tree.find('//MaxLoops')
            cycle.text = str(arg.cycle)
            if arg.stoponfail == 'on':
                stoponfail = tree.find('//MaxFailsEnabled')
                stoponfail.text = 'true'
            elif arg.stoponfail == 'off':
                stoponfail = tree.find('//MaxFailsEnabled')
                stoponfail.text = 'false'
            DelayAfterResumed = tree.find('//DelayAfterResumed')
            DelayAfterResumed.text = str(arg.delay)
            suspend=tree.find('//SleepTime')
            suspend.text = str(arg.suspend)
            tree.write(script_path, encoding='utf-8', pretty_print=True, xml_declaration=True)
            os.system(f'{self.winLR_tool_path} start {script_path}')
        elif arg.subitem == 'S3':
            script_path = os.path.join(self.winLRfolder_tool_path, 'wiLongRun', 'S3.Scenario')
            tree = etree.parse(script_path, parser_xml)
            cycle = tree.find('//MaxLoops')
            cycle.text = str(arg.cycle)
            if arg.stoponfail == 'on':
                stoponfail = tree.find('//MaxFailsEnabled')
                stoponfail.text = 'true'
            elif arg.stoponfail == 'off':
                stoponfail = tree.find('//MaxFailsEnabled')
                stoponfail.text = 'false'
            DelayAfterResumed = tree.find('//DelayAfterResumed')
            DelayAfterResumed.text = str(arg.delay)
            suspend = tree.find('//SleepTime')
            suspend.text = str(arg.suspend)
            tree.write(script_path, encoding='utf-8', pretty_print=True, xml_declaration=True)
            os.system(f'{self.winLR_tool_path} start {script_path}')
    def create_draft_log_excel(self):
        wb = openpyxl.Workbook()
        wb.save(os.path.join(self.winLRfolder_tool_path, 'wiLongRun', 'overview_result.xlsx'))
        wb.save(os.path.join(self.winLRfolder_tool_path, 'wiLongRun', 'device_check_total.xlsx'))
if __name__=="__main__":
    a=ATS()
    a.copy_log_to_histroy()
    a.create_draft_log_excel()
    a.edit_Scenario_and_run()


